package pers.mor.tomcat.watcher;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.WatchUtil;
import cn.hutool.core.io.watch.Watcher;
import cn.hutool.log.LogFactory;
import pers.mor.tomcat.catalina.Host;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.WatchEvent;

public class DynamicDeployWatcher {

    private Host host;
    private WatchMonitor monitor;

    public DynamicDeployWatcher(Host host) {
        this.host = host;
        this.monitor = WatchUtil.createAll(host.getAbsoluteAppBase(), 1, new Watching());
        this.monitor.setDaemon(true);
    }

    public void start() {
        monitor.start();
    }

    public void stop() {
        monitor.interrupt();
    }

    protected class Watching implements Watcher{

        private void execute(WatchEvent<?> event) {

            synchronized (DynamicDeployWatcher.class) {

                String fileName = event.context().toString();

                if(fileName.toLowerCase().endsWith(".war")) {
                    File warFile = FileUtil.file(host.getAbsoluteAppBase(), fileName);
                    LogFactory.get().info("动态部署：发现新文件 {}", fileName);
                    LogFactory.get().info("目录 {} 新增 {} 文件，开始部署", host.getAbsoluteAppBase(), fileName);
                    host.parseWebapp_war(warFile);
                }
            }
        }

        @Override
        public void onCreate(WatchEvent<?> watchEvent, Path path) {
            this.execute(watchEvent);
        }

        @Override
        public void onModify(WatchEvent<?> watchEvent, Path path) {
            // this.execute(watchEvent);
        }

        @Override
        public void onDelete(WatchEvent<?> watchEvent, Path path) {
            // this.execute(watchEvent);
        }

        @Override
        public void onOverflow(WatchEvent<?> watchEvent, Path path) {
            //  this.execute(watchEvent);
        }
    }
}
